#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Nacos 配置管理 Python 示例

安装依赖:
pip install nacos-sdk-python
"""

import nacos
import time

# Nacos 服务器地址
SERVER_ADDRESSES = "localhost:8848"
NAMESPACE = "public"

# 配置信息
DATA_ID = "example.properties"
GROUP = "DEFAULT_GROUP"


def config_callback(args):
    """配置变更回调函数"""
    print(f"\n配置已更新:")
    print(f"Data ID: {args['data_id']}")
    print(f"Group: {args['group']}")
    print(f"Content:\n{args['content']}")


def main():
    # 1. 创建客户端
    client = nacos.NacosClient(
        SERVER_ADDRESSES,
        namespace=NAMESPACE,
        # 如果需要认证
        # username="nacos",
        # password="nacos"
    )
    
    # 2. 发布配置
    config_content = """
server.port=8080
spring.application.name=python-example
logging.level.root=INFO
database.url=jdbc:mysql://localhost:3306/test
database.username=root
database.password=password
    """.strip()
    
    result = client.publish_config(DATA_ID, GROUP, config_content)
    print(f"发布配置: {'成功' if result else '失败'}")
    
    # 3. 获取配置
    config = client.get_config(DATA_ID, GROUP)
    print(f"\n当前配置:\n{config}")
    
    # 4. 添加配置监听器
    client.add_config_watcher(DATA_ID, GROUP, config_callback)
    print(f"\n已添加配置监听器，等待配置变更...")
    
    # 5. 模拟配置更新
    time.sleep(5)
    updated_content = config_content.replace("server.port=8080", "server.port=8081")
    client.publish_config(DATA_ID, GROUP, updated_content)
    
    # 保持监听
    print("\n监听配置变化中... (按 Ctrl+C 退出)")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n程序退出")
        # 6. 可选：删除配置
        # client.remove_config(DATA_ID, GROUP)


if __name__ == "__main__":
    main()

